#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>
#include "log.hpp"

// using func_t = std::function<std::string(const std::string&, const std::string&, u_int16_t)>;

extern Log lg;

enum
{
    SOCK_ERR = 1,
    BIND_ERR
};

u_int16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

class UdpServer
{
public:
    UdpServer(const u_int16_t port = defaultport, const std::string &ip = defaultip)
        : port_(port), ip_(ip)
    {}

    void Run()
    {
        isrunning_ = true;
        char inbuffer[size];
        while (isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }

            u_int16_t clientport = ntohs(client.sin_port);        // 将网络字节序的端口号转换为主机字节序的端口号
            std::string clientip = inet_ntoa(client.sin_addr);    // 将网络字节序的ip地址转换为点分十进制的ip地址
            
            CheckUser(client, clientip, clientport);    // 检查该用户是否存在

            std::string info = inbuffer;
            Broadcast(info, clientip, clientport);      // 广播消息
        }
    }

    void CheckUser(const struct sockaddr_in &client, const std::string &clientip, const u_int16_t clientport)
    {
        auto it = online_user_.find(clientip);
        if (it == online_user_.end())   // 该用户不存在, 则插入该用户
        {
            online_user_.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "] is online" << std::endl;
        }
    }

    void Broadcast(const std::string &info, const std::string &clientip, const u_int16_t clientport)
    {
        // 遍历在线用户, 给每个用户发送消息
        for (const auto &user : online_user_)
        {
            std::string message = "[" + clientip + ":" + std::to_string(clientport) + "]#" + info;
            socklen_t len = sizeof(user.second);
            sendto(sockfd_, message.c_str(), message.size(), 0, (struct sockaddr *)&user.second, len);
        }
    }

    void Init()
    {
        // 创建 udp socket
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", sockfd_);
            exit(SOCK_ERR);
        }
        lg(Info, "socket create success, sockfd: %d", sockfd_);
        // 2. bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);                  // 需要保证我的端口号是网络字节序列，因为端口号是要给对方发送的
        local.sin_addr.s_addr = inet_addr(ip_.c_str()); // 1. string -> u_int32_t  2. u_int32_t必须是网络序列的

        if (bind(sockfd_, (const struct sockaddr *)&local, sizeof(local)))
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success");
    }

    ~UdpServer()
    {
        if (sockfd_ > 0)
            close(sockfd_);
    }

private:
    int sockfd_; // 网络文件描述符
    std::string ip_;
    u_int16_t port_; // 表明服务器进程的端口号
    bool isrunning_;
    std::unordered_map<std::string, struct sockaddr_in> online_user_;   // 存储在线用户的ip地址和端口号
};